<template>
  <div class="init-view-wrapper">
    <div class="init-container">
      <h1 class="title">AGV智能巡检系统</h1>

      <el-collapse v-model="activeCollapseItems" class="check-list">
        <el-collapse-item
            v-for="(item, index) in checkItems"
            :key="index"
            :name="index"
            :disabled="item.status === 'loading'"
        >
          <template #title>
            <div class="check-header">
              <el-icon class="check-icon" :class="item.status">
                <component :is="statusIcons[item.status]" />
              </el-icon>
              <span>{{ item.title }}</span>
            </div>
          </template>
          <div class="check-content">
            <p v-if="item.errorMessage" class="error-message">
              错误详情: {{ item.errorMessage }}
            </p>
            <p>解决方案：{{ item.solution }}</p>
          </div>
        </el-collapse-item>
      </el-collapse>

      <div class="operate-btn-group">
        <AppButton circle :icon="Setting" @click="openSettingsModal" />
        <el-button type="success" :disabled="!allChecksPassed" @click="enterSystem">
          进入系统
        </el-button>
        <el-button type="primary" :loading="isChecking" @click="runAllChecks">
          重新检测
        </el-button>
      </div>
    </div>

    <AppModal v-model:visible="settingsModalVisible" title="系统设置" width="600px">
      <SettingsView v-if="settingsModalVisible" @save-success="handleSettingsSaved" @cancel="handleCancel" />
    </AppModal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElCollapse, ElCollapseItem, ElIcon, ElButton, ElMessage } from 'element-plus';
import {
  Loading,
  SuccessFilled,
  CircleCloseFilled,
  Setting
} from '@element-plus/icons-vue';

// 导入我们自己的组件和API
import AppButton from '@/components/common/AppButton.vue';
import AppModal from '@/components/common/AppModal.vue';
import SettingsView from './SettingsView.vue'; // 引入设置视图
import { checkFs, checkDb, checkAgv, checkCam } from '@/api/system';
import { sleep } from '@/utils';

const router = useRouter();

// --- State ---

const isChecking = ref(false);
const activeCollapseItems = ref([]); // 控制展开的项
const settingsModalVisible = ref(false);

// 定义所有检查项
const checkItems = reactive([
  {
    title: '正在检查系统文件完整性',
    status: 'success', // 'loading', 'success', 'error'
    api: checkFs,
    solution: '请重新安装本系统。',
    errorMessage: '',
  },
  {
    title: '正在检测数据库系统连接',
    status: 'success',
    api: checkDb,
    solution: '请检查数据库连接设置是否正确。',
    errorMessage: '',
  },
  {
    title: '正在与车辆控制系统通信',
    status: 'success',
    api: checkAgv,
    solution: '请检查巡检车IP与端口配置是否正确。',
    errorMessage: '',
  },
  {
    title: '正在检测摄像头通道状态',
    status: 'success',
    api: checkCam,
    solution: '请检查摄像头IP及账号密码是否正确。',
    errorMessage: '',
  },
]);

const statusIcons = {
  loading: Loading,
  success: SuccessFilled,
  error: CircleCloseFilled,
};

// --- Computed ---

// 计算是否所有检查都已成功
const allChecksPassed = computed(() => {
  return checkItems.every(item => item.status === 'success');
});

// --- Methods ---

// 执行单个检查
const runCheck = async (item, index) => {
  item.status = 'loading';
  item.errorMessage = '';
  // TODO: 正在检查 undefine
  item.title = item.title.replace(/检查完毕.*/, '正在' + item.title.split('正在')[1]);
  try {
    await sleep(300); // 增加一点延迟，提升视觉效果
    let {data} = await item.api();
    if(data.code === "200"){
      item.status = 'success';
    }else{
      item.status = 'error';
    }
    item.title = item.title.replace('正在', '检查完毕-');
  } catch (error) {
    item.status = 'error';
    item.errorMessage = error.message || '连接失败或超时';
    item.title = item.title.replace('正在', '检查完毕-');
    // 如果有错误，自动展开对应的面板
    if (!activeCollapseItems.value.includes(index)) {
      activeCollapseItems.value.push(index);
    }
  }
};

// 执行所有检查
const runAllChecks = async () => {
  if (isChecking.value) return;
  isChecking.value = true;
  activeCollapseItems.value = []; // 重置时折叠所有面板

  for (let i = 0; i < checkItems.length; i++) {
    await runCheck(checkItems[i], i);
  }

  isChecking.value = false;
  if (allChecksPassed.value) {
    ElMessage.success('系统自检全部通过！');
  } else {
    ElMessage.error('系统自检发现问题，请根据提示处理。');
  }
};

// 进入主系统
const enterSystem = () => {
  if (allChecksPassed.value) {
    router.push('/tasks');
  } else {
    ElMessage.warning('系统自检未通过，无法进入系统。');
  }
};

// 处理设置
const openSettingsModal = () => {
  settingsModalVisible.value = true;
};

const handleSettingsSaved = () => {
  settingsModalVisible.value = false;
  ElMessage.info('配置已更新，将为您重新执行系统自检。');
  // 保存设置后重新进行检测
  runAllChecks();
};

const handleCancel = () => {
  settingsModalVisible.value = false;
};

// --- Lifecycle Hooks ---

onMounted(() => {
  runAllChecks();
});
</script>

<style lang="scss" scoped>
@use '../assets/scss/variables' as *;

.init-view-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: $bg-color;
}

.init-container {
  width: 450px;
  background: white;
  padding: 30px 40px;
  border-radius: $border-radius-large;
  box-shadow: $box-shadow-base;
}

.title {
  text-align: center;
  margin-bottom: 40px;
  color: $text-color-primary;
  font-size: $font-size-extra-large;
}

.check-list {
  border-top: none;
  border-bottom: none;
}

.check-header {
  display: flex;
  align-items: center;
  font-size: $font-size-base;
}

.check-icon {
  margin-right: 12px;
  font-size: 20px;

  &.loading {
    animation: spin 1.5s linear infinite;
    color: $primary-color;
  }
  &.success {
    color: $success-color;
  }
  &.error {
    color: $danger-color;
  }
}

.check-content {
  padding: 10px 0 10px 32px;
  font-size: $font-size-small;
  color: $text-color-regular;
  line-height: 1.6;

  .error-message {
    color: $danger-color;
    font-weight: bold;
    margin-bottom: 5px;
  }
}

.operate-btn-group {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 深度修改Element Plus组件样式
:deep(.el-collapse-item__header) {
  height: 56px;
  border-bottom: 1px solid $border-color-light;
}
:deep(.el-collapse-item__wrap) {
  border-bottom: 1px solid $border-color-light;
}
:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
</style>